import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Menu, Row, Col, Tree, Button, Modal, Spin, Alert } from 'antd';
import styles from './Users.css';
import moment from 'moment';
import Factory from '../factory';
import * as datetime from '../../utils/datetime'
import dataTableCreate from '../addons/DataTable'
import * as commonService from '../../services/CommonCRUD';
import * as menuService from '../../services/menus';
const daoName = "Role";
const DataTable = dataTableCreate(daoName);
const TreeNode = Tree.TreeNode;
class RolePopedom extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            isDisabled: true,
            roleID: 0
        };
    }
    componentDidMount() {
        this.props.dispatch({
            type: `popedom/fetchRoles`,
            payload: { daoName, permID: "1032" }
        });
        this.props.dispatch({
            type: `popedom/fetchPermTree`,
            payload: { daoName, permID: "1032" }

        });
        this.props.dispatch({
            type: `popedom/fetchUserTree`,
            payload: { daoName, permID: "1032" }

        });
    }
    selectChangeHandler(e) {
        let roleID = e.key
        if (roleID !== undefined) {
            this.state.isDisabled = false
        }
        this.state.roleID = e.key
        this.props.dispatch({
            type: `popedom/fetchPermTreeCheckedKeys`,
            payload: { roleID }
        });
        this.props.dispatch({
            type: `popedom/fetchUserTreeCheckedKeys`,
            payload: { roleID }
        });
    }
    onPermTreeCheck = (permTreeCheckedKeys) => {
        this.props.dispatch({
            type: `popedom/savePermTreeCheckedKeys`,
            payload: { permTreeCheckedKeys }
        });
    }
    onUserTreeCheck = (userTreeCheckedKeys) => {
        this.props.dispatch({
            type: `popedom/saveUserTreeCheckedKeys`,
            payload: { userTreeCheckedKeys }
        });
    }
    roleSubmit() {
        let { permTreeCheckedKeys, userTreeCheckedKeys, roleDatas } = this.props;
        let roleID = this.state.roleID
        let roleName = ""
        for (let i = 0; i < roleDatas.length; i++) {
            if (Number(roleDatas[i].ID) === Number(roleID)) {
                roleName = roleDatas[i].Name
                break
            }
        }
        Modal.confirm({
            title: '提示',
            content: `你确认授予角色 '${roleName}' 权限吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                menuService.rolePermsSave({ roleID, permTreeCheckedKeys, userTreeCheckedKeys }
                ).then(function (data) {
                    if (data === "OK") {
                        message.success("权限保存成功！")
                    }
                }.bind(this)).catch(function (ex) {
                    message.error(ex.toString())
                });
            }
        });
    }
    clearRole() {
        let { roleDatas } = this.props;
        let roleID = this.state.roleID
        let roleName = ""
        for (let i = 0; i < roleDatas.length; i++) {
            if (Number(roleDatas[i].ID) === Number(roleID)) {
                roleName = roleDatas[i].Name
                break
            }
        }
        const permTreeCheckedKeys = []
        const userTreeCheckedKeys = []
        Modal.confirm({
            title: '提示',
            content: `你确认清空角色 '${roleName}' 的所有权限吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                menuService.rolePermsSave({ roleID, permTreeCheckedKeys, userTreeCheckedKeys }
                ).then(function (data) {
                    if (data === "OK") {
                        this.props.dispatch({
                            type: `popedom/savePermTreeCheckedKeys`,
                            payload: { permTreeCheckedKeys }
                        });
                        this.props.dispatch({
                            type: `popedom/saveUserTreeCheckedKeys`,
                            payload: { userTreeCheckedKeys }
                        });
                        message.success("权限清空成功！")
                    }
                }.bind(this)).catch(function (ex) {
                    message.error(ex.toString())
                });
            }
        });

    }
    render() {
        let { offsetHeight, roleDatas, permTreeNodes, UserTreeNodes, permTreeCheckedKeys, userTreeCheckedKeys } = this.props;
        if (roleDatas.length === 0 || permTreeNodes.length === 0 || UserTreeNodes.length === 0) {
            return (
                <Spin tip="页面加载中...">
                    <Alert
                        message="角色权限设置"
                        description="页面正在加载中，请您稍等..."
                        type="info"
                    />
                </Spin>
            )
        } else {
            let items = []
            if (roleDatas !== undefined) {
                roleDatas.map(d => {
                    items.push(<Menu.Item key={d.ID}>{<span>{d.Name}</span>}</Menu.Item>)
                })
            }
            const loop = treeDatas => treeDatas.map((item) => {
                if (item.children) {
                    return (
                        <TreeNode key={item.key} title={item.title} >
                            {loop(item.children)}
                        </TreeNode>
                    );
                }
                return <TreeNode key={item.key} title={item.title} />;
            });
            const loopU = UserTreeDatas => UserTreeDatas.map((item) => {
                if (item.children) {
                    return (
                        <TreeNode key={item.key} title={item.title} >
                            {loopU(item.children)}
                        </TreeNode>
                    );
                }
                return <TreeNode key={item.key} title={item.title} />;
            });
            return (
                <div className={styles.normal} style={{ background: '#ECECEC', marginTop: -16, padding: '5px 5px' }} >
                    <Row>
                        <Col span={6} style={{ paddingRight: 15 }}>
                            <div style={{ height: offsetHeight - 100, overflow: "auto" }}>
                                <Menu mode="inline"
                                    height={offsetHeight - 100}
                                    onClick={this.selectChangeHandler.bind(this)}
                                >
                                    {items}
                                </Menu>
                            </div>
                        </Col>
                        <Col span={9} style={{ paddingRight: 15 }}>
                            <div style={{ height: offsetHeight - 150, overflow: "auto", background: "#fff" }}>
                                <Tree
                                    checkable
                                    onCheck={this.onPermTreeCheck}
                                    checkedKeys={permTreeCheckedKeys}
                                >
                                    {loop(permTreeNodes)}
                                </Tree>
                            </div>
                        </Col>
                        <Col span={9}>
                            <div style={{ height: offsetHeight - 150, overflow: "auto", background: "#fff" }}>
                                <Tree
                                    checkable
                                    onCheck={this.onUserTreeCheck}
                                    checkedKeys={userTreeCheckedKeys}
                                >
                                    {loopU(UserTreeNodes)}
                                </Tree>
                            </div>
                        </Col>
                        <Col span={18}>
                            <div style={{ marginTop: 10 }}>
                                <Row>
                                    <Col span={12} >
                                        <span style={{ float: "right", marginRight: 10 }}>
                                            <Button type="primary" disabled={this.state.isDisabled} onClick={this.roleSubmit.bind(this)}>保存</Button>
                                        </span>
                                    </Col>
                                    <Col span={12} >
                                        <span style={{ float: "left", marginLeft: 10 }}>
                                            <Button type="primary" disabled={this.state.isDisabled} onClick={this.clearRole.bind(this)}>清除</Button>
                                        </span>
                                    </Col>
                                </Row>
                            </div>
                        </Col>
                    </Row>
                </div>
            )
        }
    }
}

function mapStateToProps(state) {
    const { roleDatas, permTreeNodes, UserTreeNodes, permTreeCheckedKeys, userTreeCheckedKeys } = state.popedom;
    const { offsetHeight } = state.menus
    return {
        roleDatas,
        permTreeNodes,
        UserTreeNodes,
        offsetHeight,
        permTreeCheckedKeys,
        userTreeCheckedKeys
    }
}
RolePopedom = connect(mapStateToProps)(RolePopedom)
export default RolePopedom;

let render = (props) => React.createElement(RolePopedom, props);
let f = new Factory()
f.set("RolePopedom", render)
